{% extends 'assets/base.html' %}
{% load static %}

{% block title %}移动端资产扫码 - 固定资产管理系统{% endblock %}

{% block extra_css %}
<style>
    .mobile-container {
        max-width: 500px;
        margin: 0 auto;
        padding: 20px;
    }
    
    .scan-card {
        background: white;
        border-radius: 15px;
        padding: 30px;
        text-align: center;
        box-shadow: 0 4px 20px rgba(0,0,0,0.1);
        margin-bottom: 20px;
    }
    
    .camera-container {
        position: relative;
        width: 100%;
        max-width: 400px;
        margin: 20px auto;
        border-radius: 10px;
        overflow: hidden;
        background: #000;
    }
    
    #video {
        width: 100%;
        height: auto;
        display: block;
    }
    
    .scan-overlay {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        width: 200px;
        height: 200px;
        border: 2px solid #00ff00;
        border-radius: 10px;
        pointer-events: none;
    }
    
    .scan-overlay::before,
    .scan-overlay::after {
        content: '';
        position: absolute;
        width: 20px;
        height: 20px;
        border: 3px solid #00ff00;
    }
    
    .scan-overlay::before {
        top: -3px;
        left: -3px;
        border-right: none;
        border-bottom: none;
    }
    
    .scan-overlay::after {
        bottom: -3px;
        right: -3px;
        border-left: none;
        border-top: none;
    }
    
    .scan-line {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 2px;
        background: linear-gradient(90deg, transparent, #00ff00, transparent);
        animation: scan 2s linear infinite;
    }
    
    @keyframes scan {
        0% { top: 0; }
        100% { top: 100%; }
    }
    
    .control-buttons {
        margin-top: 20px;
    }
    
    .control-buttons .btn {
        margin: 5px;
        border-radius: 25px;
        padding: 10px 20px;
    }
    
    .result-card {
        background: #d4edda;
        border: 1px solid #c3e6cb;
        border-radius: 10px;
        padding: 20px;
        margin-top: 20px;
        display: none;
    }
    
    .error-card {
        background: #f8d7da;
        border: 1px solid #f5c6cb;
        border-radius: 10px;
        padding: 20px;
        margin-top: 20px;
        display: none;
    }
    
    .asset-info {
        text-align: left;
        margin-top: 15px;
    }
    
    .asset-info .row {
        margin-bottom: 10px;
    }
    
    .manual-input {
        margin-top: 20px;
        padding-top: 20px;
        border-top: 1px solid #dee2e6;
    }
    
    @media (max-width: 768px) {
        .mobile-container {
            padding: 10px;
        }
        
        .scan-card {
            padding: 20px;
        }
        
        .camera-container {
            max-width: 100%;
        }
    }
</style>
{% endblock %}

{% block content %}
<div class="mobile-container">
    <div class="scan-card">
        <h3><i class="fas fa-qrcode"></i> 资产扫码查询</h3>
        <p class="text-muted">将摄像头对准资产二维码进行扫描</p>
        
        <div class="camera-container" id="cameraContainer">
            <video id="video" autoplay muted playsinline></video>
            <div class="scan-overlay">
                <div class="scan-line"></div>
            </div>
        </div>
        
        <div class="control-buttons">
            <button id="startScanBtn" class="btn btn-primary">
                <i class="fas fa-camera"></i> 开始扫描
            </button>
            <button id="stopScanBtn" class="btn btn-secondary" style="display: none;">
                <i class="fas fa-stop"></i> 停止扫描
            </button>
            <button id="switchCameraBtn" class="btn btn-outline-info" style="display: none;">
                <i class="fas fa-sync-alt"></i> 切换摄像头
            </button>
        </div>
        
        <!-- 手动输入 -->
        <div class="manual-input">
            <h6>或手动输入资产编号</h6>
            <div class="input-group">
                <input type="text" id="manualInput" class="form-control" placeholder="输入资产编号...">
                <button class="btn btn-outline-primary" id="manualSearchBtn">
                    <i class="fas fa-search"></i> 查询
                </button>
            </div>
        </div>
    </div>
    
    <!-- 扫描结果 -->
    <div class="result-card" id="resultCard">
        <h5><i class="fas fa-check-circle text-success"></i> 扫描成功</h5>
        <div class="asset-info" id="assetInfo">
            <!-- 资产信息将在这里显示 -->
        </div>
        <div class="mt-3">
            <button class="btn btn-primary" id="viewDetailBtn">
                <i class="fas fa-eye"></i> 查看详情
            </button>
            <button class="btn btn-outline-secondary" id="scanAgainBtn">
                <i class="fas fa-qrcode"></i> 继续扫描
            </button>
        </div>
    </div>
    
    <!-- 错误信息 -->
    <div class="error-card" id="errorCard">
        <h5><i class="fas fa-exclamation-triangle text-danger"></i> 扫描失败</h5>
        <p id="errorMessage"></p>
        <button class="btn btn-outline-secondary" id="retryBtn">
            <i class="fas fa-redo"></i> 重试
        </button>
    </div>
    
    <!-- 扫描历史 -->
    <div class="scan-card">
        <h5><i class="fas fa-history"></i> 最近扫描</h5>
        <div id="scanHistory">
            <p class="text-muted">暂无扫描记录</p>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script src="https://cdn.jsdelivr.net/npm/jsqr@1.4.0/dist/jsQR.js"></script>
<script>
class AssetScanner {
    constructor() {
        this.video = document.getElementById('video');
        this.canvas = document.createElement('canvas');
        this.context = this.canvas.getContext('2d');
        this.stream = null;
        this.scanning = false;
        this.cameras = [];
        this.currentCameraIndex = 0;
        
        this.initializeElements();
        this.bindEvents();
        this.loadScanHistory();
    }
    
    initializeElements() {
        this.startBtn = document.getElementById('startScanBtn');
        this.stopBtn = document.getElementById('stopScanBtn');
        this.switchBtn = document.getElementById('switchCameraBtn');
        this.resultCard = document.getElementById('resultCard');
        this.errorCard = document.getElementById('errorCard');
        this.assetInfo = document.getElementById('assetInfo');
        this.errorMessage = document.getElementById('errorMessage');
        this.manualInput = document.getElementById('manualInput');
        this.scanHistory = document.getElementById('scanHistory');
    }
    
    bindEvents() {
        this.startBtn.addEventListener('click', () => this.startScanning());
        this.stopBtn.addEventListener('click', () => this.stopScanning());
        this.switchBtn.addEventListener('click', () => this.switchCamera());
        
        document.getElementById('manualSearchBtn').addEventListener('click', () => {
            const assetNumber = this.manualInput.value.trim();
            if (assetNumber) {
                this.searchAsset(assetNumber);
            }
        });
        
        this.manualInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                const assetNumber = this.manualInput.value.trim();
                if (assetNumber) {
                    this.searchAsset(assetNumber);
                }
            }
        });
        
        document.getElementById('scanAgainBtn').addEventListener('click', () => {
            this.hideResults();
            this.startScanning();
        });
        
        document.getElementById('retryBtn').addEventListener('click', () => {
            this.hideResults();
            this.startScanning();
        });
    }
    
    async startScanning() {
        try {
            // 获取可用摄像头
            const devices = await navigator.mediaDevices.enumerateDevices();
            this.cameras = devices.filter(device => device.kind === 'videoinput');
            
            if (this.cameras.length === 0) {
                throw new Error('未找到可用摄像头');
            }
            
            // 优先使用后置摄像头
            const constraints = {
                video: {
                    deviceId: this.cameras[this.currentCameraIndex]?.deviceId,
                    facingMode: 'environment',
                    width: { ideal: 1280 },
                    height: { ideal: 720 }
                }
            };
            
            this.stream = await navigator.mediaDevices.getUserMedia(constraints);
            this.video.srcObject = this.stream;
            
            this.scanning = true;
            this.startBtn.style.display = 'none';
            this.stopBtn.style.display = 'inline-block';
            
            if (this.cameras.length > 1) {
                this.switchBtn.style.display = 'inline-block';
            }
            
            this.hideResults();
            this.scanFrame();
            
        } catch (error) {
            console.error('启动摄像头失败:', error);
            this.showError('无法启动摄像头: ' + error.message);
        }
    }
    
    stopScanning() {
        this.scanning = false;
        
        if (this.stream) {
            this.stream.getTracks().forEach(track => track.stop());
            this.stream = null;
        }
        
        this.video.srcObject = null;
        this.startBtn.style.display = 'inline-block';
        this.stopBtn.style.display = 'none';
        this.switchBtn.style.display = 'none';
    }
    
    async switchCamera() {
        if (this.cameras.length <= 1) return;
        
        this.currentCameraIndex = (this.currentCameraIndex + 1) % this.cameras.length;
        
        if (this.scanning) {
            this.stopScanning();
            await new Promise(resolve => setTimeout(resolve, 100));
            this.startScanning();
        }
    }
    
    scanFrame() {
        if (!this.scanning) return;
        
        if (this.video.readyState === this.video.HAVE_ENOUGH_DATA) {
            this.canvas.width = this.video.videoWidth;
            this.canvas.height = this.video.videoHeight;
            this.context.drawImage(this.video, 0, 0);
            
            const imageData = this.context.getImageData(0, 0, this.canvas.width, this.canvas.height);
            const code = jsQR(imageData.data, imageData.width, imageData.height);
            
            if (code) {
                this.handleScanResult(code.data);
                return;
            }
        }
        
        requestAnimationFrame(() => this.scanFrame());
    }
    
    handleScanResult(data) {
        console.log('扫描结果:', data);
        
        try {
            // 尝试解析二维码数据
            const qrData = JSON.parse(data);
            
            if (qrData.asset_number) {
                this.searchAsset(qrData.asset_number);
            } else {
                // 如果不是JSON格式，直接作为资产编号搜索
                this.searchAsset(data);
            }
        } catch (e) {
            // 如果不是JSON格式，直接作为资产编号搜索
            this.searchAsset(data);
        }
    }
    
    async searchAsset(assetNumber) {
        try {
            this.stopScanning();
            
            const response = await fetch(`/assets/api/asset-search/?q=${encodeURIComponent(assetNumber)}`);
            const result = await response.json();
            
            if (result.success && result.asset) {
                this.showAssetInfo(result.asset);
                this.addToHistory(result.asset);
            } else {
                this.showError(result.message || '未找到对应资产');
            }
        } catch (error) {
            console.error('搜索资产失败:', error);
            this.showError('搜索失败，请检查网络连接');
        }
    }
    
    showAssetInfo(asset) {
        this.assetInfo.innerHTML = `
            <div class="row">
                <div class="col-4"><strong>资产编号:</strong></div>
                <div class="col-8">${asset.asset_number}</div>
            </div>
            <div class="row">
                <div class="col-4"><strong>资产名称:</strong></div>
                <div class="col-8">${asset.name}</div>
            </div>
            <div class="row">
                <div class="col-4"><strong>资产类别:</strong></div>
                <div class="col-8">${asset.category}</div>
            </div>
            <div class="row">
                <div class="col-4"><strong>所属部门:</strong></div>
                <div class="col-8">${asset.department || '未分配'}</div>
            </div>
            <div class="row">
                <div class="col-4"><strong>使用人:</strong></div>
                <div class="col-8">${asset.user || '未分配'}</div>
            </div>
            <div class="row">
                <div class="col-4"><strong>资产状态:</strong></div>
                <div class="col-8">
                    <span class="badge bg-info">${asset.status_display}</span>
                </div>
            </div>
        `;
        
        document.getElementById('viewDetailBtn').onclick = () => {
            window.location.href = `/assets/assets/${asset.id}/`;
        };
        
        this.resultCard.style.display = 'block';
        this.errorCard.style.display = 'none';
    }
    
    showError(message) {
        this.errorMessage.textContent = message;
        this.errorCard.style.display = 'block';
        this.resultCard.style.display = 'none';
    }
    
    hideResults() {
        this.resultCard.style.display = 'none';
        this.errorCard.style.display = 'none';
    }
    
    addToHistory(asset) {
        let history = JSON.parse(localStorage.getItem('scanHistory') || '[]');
        
        // 避免重复
        history = history.filter(item => item.asset_number !== asset.asset_number);
        
        // 添加到开头
        history.unshift({
            ...asset,
            scan_time: new Date().toISOString()
        });
        
        // 只保留最近10条
        history = history.slice(0, 10);
        
        localStorage.setItem('scanHistory', JSON.stringify(history));
        this.updateHistoryDisplay();
    }
    
    loadScanHistory() {
        this.updateHistoryDisplay();
    }
    
    updateHistoryDisplay() {
        const history = JSON.parse(localStorage.getItem('scanHistory') || '[]');
        
        if (history.length === 0) {
            this.scanHistory.innerHTML = '<p class="text-muted">暂无扫描记录</p>';
            return;
        }
        
        const historyHtml = history.map(item => `
            <div class="d-flex justify-content-between align-items-center py-2 border-bottom">
                <div>
                    <strong>${item.asset_number}</strong><br>
                    <small class="text-muted">${item.name}</small>
                </div>
                <div class="text-end">
                    <small class="text-muted">${new Date(item.scan_time).toLocaleString()}</small><br>
                    <a href="/assets/assets/${item.id}/" class="btn btn-sm btn-outline-primary">查看</a>
                </div>
            </div>
        `).join('');
        
        this.scanHistory.innerHTML = historyHtml;
    }
}

// 页面加载完成后初始化扫描器
document.addEventListener('DOMContentLoaded', function() {
    // 检查是否支持摄像头
    if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
        document.getElementById('errorCard').style.display = 'block';
        document.getElementById('errorMessage').textContent = '您的浏览器不支持摄像头功能';
        document.getElementById('startScanBtn').style.display = 'none';
        return;
    }
    
    new AssetScanner();
});
</script>
{% endblock %}